﻿package effects {
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.GradientType;
	import flash.filters.BlurFilter;
	import flash.filters.ColorMatrixFilter;
	import flash.events.TimerEvent;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Matrix;
	import flash.utils.Timer;

	public class FireEffect extends MovieClip
	{
		public static const HEIGHT: Number = 64;
		public static const WIDTH: Number = 313;
		public static const UPDATE_TIME: uint = 100;
		public static const BLUR_X: Number = 10;
		public static const BLUR_Y: Number = 25;
		
		public var fireColor: uint = 0xFF0000;

		private var bm: Bitmap;
		private var bmd: BitmapData;
		private var effect: ColorMatrixFilter;
		private var blur: BlurFilter;
		private var updateTimer: Timer
		private var fireList: Array;
		
		
		public function FireEffect()
		{
			trace("INF: FireEffect();")
			addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
		}
		
		private function addedToStageHandler(event:Event):void
		{
			effect = new ColorMatrixFilter([3, 0, 0, 0, 0,
										    0, 2, 0, 0, 0, 
										    0, 0, 1, 0, 0, 
										    0, 0, 0, 0.7, -20]);
			
			blur = new BlurFilter(BLUR_X, BLUR_Y)
			
			fireList = [];
			
			
			bmd = new BitmapData(WIDTH, HEIGHT);
			bm = new Bitmap(bmd);
			addChild(bm);
			var h: Number = 64 - 10
			for (var i:int = 0; i < 40; i++)
			{
				var f: Sprite = fireElement();
				f.x = Math.random() * 313;
				f.y = h;
				addChild(f);
				fireList.push(f);
			}
			
			updateTimer = new Timer(UPDATE_TIME);
			updateTimer.addEventListener(TimerEvent.TIMER, updateTimerHandler)
			updateTimer.start();
		}
		
		
		private function fireElement():Sprite
		{
			var mc: Sprite = new Sprite();
			with(mc.graphics)
			{
				beginGradientFill(GradientType.RADIAL, [0xFDC571, 0xCF6A05], [1.0, 0.0], [0, 20]);
				drawCircle(0, 0, 20);
				endFill();
			}
			mc.filters = [new BlurFilter(8, 8)];
			return mc;
		}
		
		
		private function updateTimerHandler(event:TimerEvent):void
		{
			var destPoint: Point = new Point(0, 0);
			var len: int = fireList.length;
			for(var i:int = 0; i < len; i++) 
			{
				fireList[i].x += Math.random() * 6 - 3;
			}
			bmd.draw(this);
			bmd.scroll(0, -5);
			bmd.applyFilter(bmd, bmd.rect, destPoint, blur);
			//bmd.applyFilter(bmd, bmd.rect, destPoint, effect);
		}
	}
}